package com.xuecheng.rabbitmq.header;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeoutException;

public class HeaderProducer {
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    //不处理路由键交换机名称
    private static final String EXCHANGE_FANOUT_INFORM = "exchange_header_inform";

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("47.99.79.246");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("/");
        //创建tpc连接
        Connection connection = factory.newConnection();
        //创建交换机通道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_FANOUT_INFORM, BuiltinExchangeType.HEADERS);


        //声明队列
        channel.queueDeclare(QUEUE_INFORM_EMAIL, true,false, false,null);
        channel.queueDeclare(QUEUE_INFORM_SMS, true,false, false,null);

        //绑定队列
        Map<String,Object> h_e = new Hashtable<>();
        h_e.put("inform_type","email");
        Map<String,Object> h_s = new Hashtable<>();
        h_s.put("inform_type","email");
        channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_FANOUT_INFORM,"",h_s);
        channel.queueBind(QUEUE_INFORM_EMAIL,EXCHANGE_FANOUT_INFORM,"",h_e);

        for (int i=10 ; i>0; i--) {
            String message = "eamil inform to user"+i;
            Map<String,Object> headers = new Hashtable<>();
            headers.put("inform_type","email");//匹配email 通知消费者绑定的header
            AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties.Builder();
            builder.headers(headers);
            //email通知
            channel.basicPublish(EXCHANGE_FANOUT_INFORM,"", builder.build(),message.getBytes());
        }

    }
}

